# pip install pdf2docx
import os
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from pathlib import Path
from pdf2docx import Converter
import threading

class PdfToWordApp:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("PDF转Word转换器 v2.0")
        self.root.geometry("680x500")
        self.setup_ui()
        self.converting = False
        
    def setup_ui(self):
        # 主框架
        main_frame = tk.Frame(self.root, padx=20, pady=15)
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 文件选择区域
        input_frame = tk.LabelFrame(main_frame, text="输入设置", padx=10, pady=10)
        input_frame.pack(fill=tk.X, pady=5)
        
        # 转换模式选择
        mode_frame = tk.Frame(input_frame)
        mode_frame.pack(fill=tk.X, pady=5)
        tk.Label(mode_frame, text="转换模式:").pack(side=tk.LEFT)
        
        self.convert_mode = tk.StringVar(value="single")
        tk.Radiobutton(mode_frame, text="单个文件", 
                      variable=self.convert_mode, value="single").pack(side=tk.LEFT)
        tk.Radiobutton(mode_frame, text="批量转换", 
                      variable=self.convert_mode, value="batch").pack(side=tk.LEFT)
        
        # 输入路径选择
        path_frame = tk.Frame(input_frame)
        path_frame.pack(fill=tk.X, pady=5)
        tk.Label(path_frame, text="PDF路径:").pack(side=tk.LEFT)
        self.input_entry = tk.Entry(path_frame)
        self.input_entry.pack(side=tk.LEFT, expand=True, fill=tk.X, padx=5)
        tk.Button(path_frame, text="浏览...", command=self.select_input).pack(side=tk.LEFT)
        
        # 输出设置区域
        output_frame = tk.LabelFrame(main_frame, text="输出设置", padx=10, pady=10)
        output_frame.pack(fill=tk.X, pady=5)
        
        # 输出路径选择
        out_path_frame = tk.Frame(output_frame)
        out_path_frame.pack(fill=tk.X, pady=5)
        tk.Label(out_path_frame, text="输出目录:").pack(side=tk.LEFT)
        self.output_entry = tk.Entry(out_path_frame)
        self.output_entry.pack(side=tk.LEFT, expand=True, fill=tk.X, padx=5)
        tk.Button(out_path_frame, text="浏览...", command=self.select_output).pack(side=tk.LEFT)
        
        # 转换选项区域
        option_frame = tk.LabelFrame(main_frame, text="转换选项", padx=10, pady=10)
        option_frame.pack(fill=tk.X, pady=5)
        
        # 布局保持选项
        self.keep_layout = tk.BooleanVar(value=True)
        tk.Checkbutton(option_frame, text="保持原始布局", 
                      variable=self.keep_layout).pack(anchor=tk.W)
        
        # 图片质量选项
        qual_frame = tk.Frame(option_frame)
        qual_frame.pack(fill=tk.X, pady=5)
        tk.Label(qual_frame, text="图片质量:").pack(side=tk.LEFT)
        self.quality = tk.StringVar(value="high")
        tk.OptionMenu(qual_frame, self.quality, "high", "medium", "low").pack(side=tk.LEFT)
        
        # 进度显示区域
        progress_frame = tk.Frame(main_frame)
        progress_frame.pack(fill=tk.X, pady=10)
        
        self.progress = ttk.Progressbar(progress_frame, orient=tk.HORIZONTAL, 
                                      length=300, mode='determinate')
        self.progress.pack(side=tk.LEFT, expand=True, fill=tk.X)
        
        self.status_label = tk.Label(progress_frame, text="准备就绪")
        self.status_label.pack(side=tk.LEFT, padx=10)
        
        # 操作按钮区域
        btn_frame = tk.Frame(main_frame)
        btn_frame.pack(fill=tk.X, pady=5)
        
        tk.Button(btn_frame, text="开始转换", command=self.start_conversion,
                width=15).pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="取消", command=self.cancel_conversion,
                width=15).pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="退出", command=self.root.quit,
                width=15).pack(side=tk.RIGHT, padx=5)
    
    def select_input(self):
        if self.convert_mode.get() == "single":
            path = filedialog.askopenfilename(
                title="选择PDF文件",
                filetypes=[("PDF文件", "*.pdf"), ("所有文件", "*.*")]
            )
        else:
            path = filedialog.askdirectory(title="选择PDF文件夹")
        
        if path:
            self.input_entry.delete(0, tk.END)
            self.input_entry.insert(0, path)
    
    def select_output(self):
        path = filedialog.askdirectory(title="选择Word输出目录")
        if path:
            self.output_entry.delete(0, tk.END)
            self.output_entry.insert(0, path)
    
    def start_conversion(self):
        if self.converting:
            return
            
        input_path = self.input_entry.get()
        output_path = self.output_entry.get()
        
        if not input_path or not output_path:
            messagebox.showerror("错误", "请选择输入和输出路径")
            return
        
        # 获取文件列表
        files = []
        if self.convert_mode.get() == "batch":
            for ext in ["*.pdf", "*.PDF"]:
                files.extend(Path(input_path).glob(ext))
        else:
            files.append(Path(input_path))
        
        if not files:
            messagebox.showwarning("警告", "没有找到PDF文件")
            return
            
        # 准备转换
        self.converting = True
        self.progress["maximum"] = len(files)
        self.progress["value"] = 0
        self.status_label.config(text="准备转换...")
        
        # 启动转换线程
        threading.Thread(
            target=self.convert_files,
            args=(files, output_path),
            daemon=True
        ).start()
    
    def convert_files(self, files, output_dir):
        success = 0
        output_dir = Path(output_dir)
        
        for i, pdf_file in enumerate(files):
            if not self.converting:
                break
                
            try:
                self.update_status(f"正在转换: {pdf_file.name}", i+1)
                
                # 设置输出路径
                word_file = output_dir / f"{pdf_file.stem}.docx"
                
                # 转换PDF到Word
                cv = Converter(pdf_file)
                cv.convert(
                    word_file,
                    keep_layout=self.keep_layout.get(),
                    image_quality=self.quality.get()
                )
                cv.close()
                
                success += 1
            except Exception as e:
                print(f"转换失败 {pdf_file}: {str(e)}")
        
        self.converting = False
        self.root.after(0, lambda: messagebox.showinfo(
            "完成", 
            f"成功转换 {success}/{len(files)} 个文件"
        ))
        self.update_status("转换完成", 0)
    
    def cancel_conversion(self):
        if self.converting:
            if messagebox.askyesno("确认", "确定要取消当前转换吗？"):
                self.converting = False
                self.update_status("转换已取消", 0)
    
    def update_status(self, message, value):
        self.root.after(0, lambda: [
            self.status_label.config(text=message),
            self.progress.config(value=value)
        ])
    
    def run(self):
        self.root.mainloop()

if __name__ == "__main__":
    app = PdfToWordApp()
    app.run()
